'use strict';
import path from 'path';
// BrowserWindow: 窗口, ipcMain: 进程通信, Tray: 系统托盘,Menu: 菜单,
// screen: 屏幕, globalShortcut: 快捷键, shell: 模块提供了集成其他桌面客户端的关联功能.
import { app, protocol, BrowserWindow, session, ipcMain, Tray, Menu, screen, globalShortcut } from 'electron';
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib';

const isDevelopment = process.env.NODE_ENV !== 'production';
// 窗口弹出上下文菜单
BrowserWindow.prototype.popUpContextMenu = function (menu, options) {
  options ? menu.popup(options) : menu.popup();
};
// 页面加载基础URL
// const winURL = process.env.NODE_ENV === 'development' ? `http://localhost:8080` : `file://${__dirname}/index.html`;
const winURL = process.env.NODE_ENV === 'development' ? `http://localhost:8080` : `app://./index.html`;
//public文件夹的路径
const publicPath = __static;
// 系统字体
let fonts = [];

const appIconPath = path.join(publicPath, '/app.ico'); //软件图标
const preload = path.join(publicPath, '/preload/preload.js'); //预加载文件
let mainWindow = null; //主窗口
let editorWindowArray = {}; //编辑内容窗口
let appTray = null; //系统托盘对象
let appTrayIconPath = path.join(publicPath, '/app.ico'); //系统托盘图标路径

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([{ scheme: 'app', privileges: { secure: true, standard: true } }]);

/**
 * 监听渲染进程的事件
 */
// 主界面
ipcMain.on('mainWindow', (e, msg) => {
  // console.log(msg);
  if (msg.message == 'set') {
    mainWindow.popUpContextMenu(
      Menu.buildFromTemplate([
        {
          label: '打开调试器',
          click: (res) => {
            mainWindow.webContents.openDevTools({ mode: 'detach' });
          },
        },
      ]),
      { x: 180, y: 31 }
    );
  } else if (msg.message == 'minimize') {
    mainWindow.minimize();
  } else if (msg.message === "font") {
    mainWindow && mainWindow.webContents.send('font', fonts);
  } else if (msg.message == 'contextMenu') {
    mainWindow.popUpContextMenu(
      Menu.buildFromTemplate([
        {
          label: msg.isComplete ? "取消完成" : '完成',
          icon: path.join(publicPath, '/icon/complete.png'),
          click: () => {
            mainWindow && mainWindow.webContents.send('message', {
              text: msg.isComplete ? "取消完成" : '完成', id: msg.id
            });
          },
        },
        {
          label: '编辑',
          icon: path.join(publicPath, '/icon/edit.png'),
          click: (res) => {
            mainWindow && mainWindow.webContents.send('message', { text: '编辑', id: msg.id });
          },
        },
        {
          label: '删除',
          icon: path.join(publicPath, '/icon/delete.png'),
          click: (res) => {
            mainWindow && mainWindow.webContents.send('message', { text: '删除', id: msg.id });
          },
        }
      ])
    );
  }
});
// 编辑器窗口
ipcMain.on('editorWindow', async (e, msg) => {
  if (msg.message == 'add') {
    editorWindowArray['unique'] ? editorWindowArray['unique'].show() : await createEditorWindow('unique');
  } else if (msg.message == 'edit') {
    if (editorWindowArray[msg.id]) {
      editorWindowArray[msg.id].show();
    } else {
      await createEditorWindow(msg.id);
      editorWindowArray[msg.id].webContents.send('message', msg.id);
    }
  } else if (msg.message == 'close') {
    editorWindowArray[msg.key] && editorWindowArray[msg.key].close();
  } else if (msg.message == 'save') {
    // 点击保存好告诉主窗口数据更新了,重新获取数据
    mainWindow && mainWindow.webContents.send('message', { text: 'editorSave' });
  }
});


// 主界面
async function createWindow() {
  mainWindow = new BrowserWindow({
    width: 300,
    height: 750,
    minWidth: 300,
    minHeight: 300,
    maxWidth: 300,
    maxHeight: 750,
    frame: false,
    transparent: true,
    backgroundColor: '#00000000',
    skipTaskbar: true,
    icon: appIconPath,
    webPreferences: {
      webSecurity: false, //加上这个就可以获取到了本地的图片
      contextIsolation: false,
      enableRemoteModule: true,
      nodeIntegration: true,
      preload: preload,
    },
    alwaysOnTop: true,
  });
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // 开发环境
    await mainWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
  } else {
    createProtocol('app');
    // 正式环境
    mainWindow.loadURL('app://./index.html');
  }
  //获取显示器的宽高
  const size = screen.getPrimaryDisplay().workAreaSize;
  //设置窗口的位置 注意x轴要桌面的宽度 - 窗口的宽度
  mainWindow.setPosition(size.width - 300 - 150, 50);
  // 窗口移动
  windowMove(mainWindow, 'mainWindow');
  // 系统托盘
  createAppTray();
  // 当我们点击关闭时触发close事件，我们按照之前的思路在关闭时，隐藏窗口，隐藏任务栏窗口
  mainWindow.on('close', (event) => {
    event.preventDefault();
    mainWindow.hide();
  });
  mainWindow.on('minimize', (event) => {
    event.preventDefault();
    mainWindow.hide();
  });
  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
  });
  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}
// 系统托盘
async function createAppTray() {
  // 系统托盘图标目录
  appTray = new Tray(appTrayIconPath); // 引入托盘中的小图标本地测试相对路径
  // 设置此托盘图标的悬停提示内容
  appTray.setToolTip('幻影签');
  // 单击右下角小图标显示应用
  appTray.on('click', function () {
    mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show();
  });
  appTray.on('right-click', function () {
    // 弹出图标菜单
    appTray.popUpContextMenu(
      Menu.buildFromTemplate([
        {
          label: '主界面',
          type: 'checkbox',
          checked: mainWindow.isVisible(),
          click: (res) => {
            if (res.checked) {
              mainWindow.show();
            } else {
              mainWindow.hide();
            }
          },
        },
        {
          type: 'checkbox',
          label: '开机启动',
          checked: app.getLoginItemSettings().openAtLogin,
          click: function () {
            if (!app.isPackaged) {
              app.setLoginItemSettings({
                openAtLogin: !app.getLoginItemSettings().openAtLogin,
                path: process.execPath,
              });
            } else {
              app.setLoginItemSettings({
                openAtLogin: !app.getLoginItemSettings().openAtLogin,
              });
            }
            console.log(app.getLoginItemSettings().openAtLogin);
            console.log(!app.isPackaged);
          },
        },
        {
          type: 'separator',
        },
        {
          label: '检查更新',
          click: () => {
          },
        },
        {
          label: '关于',
          click: () => {
          },
        },
        {
          type: 'separator',
        },
        {
          label: '退出',
          icon: path.join(publicPath, '/icon/drop.png'),
          click: () => {
            app.exit();
          },
        },
      ])
    );
  });
}
// 编辑器页面
async function createEditorWindow(name) {
  editorWindowArray[name] = new BrowserWindow({
    width: 700,
    height: 500,
    resizable: false, //禁止窗口大小缩放
    icon: appIconPath,
    autoHideMenuBar: true,
    webPreferences: {
      devTools: false, //关闭调试工具
      contextIsolation: false,
      enableRemoteModule: true,
      nodeIntegration: true,
      preload: preload,
    },
  });

  // 打开调试窗口
  // editorWindowArray[name].webContents.openDevTools();

  editorWindowArray[name].setMenu(null);
  //获取显示器的宽高
  const size = screen.getPrimaryDisplay().workAreaSize;
  //设置窗口的位置 注意x轴要桌面的宽度 - 窗口的宽度
  editorWindowArray[name].setPosition((size.width - 450 - 700) / 2, size.height / 2 - 300);
  // 加载页面
  await editorWindowArray[name].loadURL(winURL + '#/editor');
  // 显示窗口
  editorWindowArray[name].show();
  // 设置窗口标题
  editorWindowArray[name].title = name === 'unique' ? '幻影签-新增内容' : '幻影签-内容编辑';

  // 事件
  editorWindowArray[name].once('ready-to-show', () => {
    editorWindowArray[name].show();
  });
  editorWindowArray[name].on('closed', () => {
    editorWindowArray[name] = null;
  });
}
/**
 * 窗口移动
 * @param win
 */
function windowMove(win, name) {
  let winStartPosition = { x: 0, y: 0 };
  let mouseStartPosition = { x: 0, y: 0 };
  let movingInterval = null;

  /**
   * 窗口移动事件
   */
  ipcMain.on('window-move-open-' + name, (events, canMoving) => {
    if (canMoving) {
      // 读取原位置
      const winPosition = win.getPosition();
      winStartPosition = { x: winPosition[0], y: winPosition[1] };
      mouseStartPosition = screen.getCursorScreenPoint();
      // 清除
      if (movingInterval) {
        clearInterval(movingInterval);
      }
      // 新开
      movingInterval = setInterval(() => {
        // 实时更新位置
        const cursorPosition = screen.getCursorScreenPoint();
        const x = winStartPosition.x + cursorPosition.x - mouseStartPosition.x;
        const y = winStartPosition.y + cursorPosition.y - mouseStartPosition.y;
        win.setPosition(x, y, true);
      }, 40);
    } else {
      clearInterval(movingInterval);
      movingInterval = null;
    }
  });
}

/**
 * 获取系统字体
 */
const fontList = require('font-list');

async function getSystemFont() {
  try {
    fonts = await fontList.getFonts();
    for (let key in fonts) {
      if (fonts.hasOwnProperty(key)) {
        fonts[key] = fonts[key].replace(/^"|"$/g, '')
      }
    }
  } catch (e) {
    console.log(e)
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      // import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer';
      // await installExtension(VUEJS_DEVTOOLS);
      session.defaultSession.loadExtension(
        path.resolve(path.join(__dirname, '../devTools/vue-devtools/')) //这个是刚刚build好的插件目录
      );
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString());
    }
  }
  // 可以加载本地文件
  protocol.interceptFileProtocol('file',
    (req, callback) => {
      const url = req.url.substr(8);
      callback(path.normalize(decodeURI(url)));
    }
  );
  // 创建主窗口
  createWindow();
  // 获取系统字体
  getSystemFont();
  /**
   * 监听键盘事件
   */
  globalShortcut.register('Ctrl+Shift+i', (e) => { });
});

// 解决透明窗口打开闪烁问题
app.commandLine.appendSwitch('wm-window-animations-disabled');

// 限制只能打开一个软件窗口
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // 当运行第二个实例时,将会聚焦到mainWindow这个窗口
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore()
      mainWindow.focus()
      mainWindow.show()
    }
  })
}

app.on('will-quit', () => {
  //注销全局快捷键
  globalShortcut.unregister('Ctrl+Shift+i');
  globalShortcut.unregisterAll();
});

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  !mainWindow && createWindow();
});